package net.sourceforge.cath.aspects.pojo;

import net.sourceforge.cath.context.Context;
import net.sourceforge.cath.context.GlobalTransaction;
import net.sourceforge.cath.logging.LogFormatter;
import net.sourceforge.cath.logging.Logger;

public abstract aspect TracerAspectStarter {
	pointcut scope();

	Logger logger = Logger.getInstance();
	
	String getThreadName(){
		return Thread.currentThread().getName();
	}
	/**
	 * 
	 */
	before():scope(){
		// getter initial starter class
		String starterName 
			= thisJoinPoint.getSignature().getDeclaringType().getName();
		
		// create global transaction id
		StringBuffer txId = new StringBuffer();
		txId.append('G');
		txId.append(System.nanoTime());

		// create global transaction context and deposit it to ThreadLocal
		GlobalTransaction gtx;
		
		// put the id into thread local		
		// if there has already global transaction id, replicate it
		GlobalTransaction inflightGtx = Context.peekGlobalTransaction();
		if(inflightGtx != null){
			gtx = inflightGtx;
		}else{
			gtx = new GlobalTransaction();
			gtx.setId(txId.toString());
			gtx.setInitiator(starterName);
			gtx.setThread(getThreadName() );
		}
		Context.pushGlobalTransaction(gtx);
		logger.startGlobalTransaction(gtx);
		logger.debug("start new global transaction starter:["+starterName+"]"+gtx.getId());
		
	}
	
	after():scope(){
		// flush log

		GlobalTransaction gtx = Context.popGlobalTransaction();
		if(gtx == null){
			logger.error("Global transaction id is null");
			return;
		}
		logger.endGlobalTransaction(gtx);
		logger.flush();
		logger.debug("finishing global transaction "+gtx.getId());
	}
	
	
}
